//
//  YWMeterHomePageViewController.m
//  maintain
//
//  Created by 郑想 on 16/2/27.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "QRCodeReaderViewController.h"
#import "UIColor+CustomColors.h"
#import "UIImage+Extension.h"
#import "YWCommonTool.h"
#import "YWConst.h"
#import "YWMacro.h"
#import "YWMeterHomePageViewController.h"
#import "YWMeterReadingManager.h"
#import "YWMeterReadingRecordViewController.h"

#import "YWThisMonthReadingMeterCount.h"
#import "UIView+Extension.h"
#import "YWQrcodeManager.h"
#import "YWScanEquipmentNotMatchVC.h"

#import "YWDoMeterReadingTableViewController.h"
#import "YWSelectMeterReadingEquipmentTableViewController.h"
#import "YWNoQrcodeRights.h"
#import "YWLoginTool.h"

@interface YWMeterHomePageViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UILabel* LBWaterMeterTodayReadCount;
@property (weak, nonatomic) IBOutlet UILabel* LBWaterMeterMonthReadCount;
@property (weak, nonatomic) IBOutlet UILabel* LBWaterMeterMonthNoReadCount;

@property (weak, nonatomic) IBOutlet UILabel* LBElectricMeterTodayReadCount;
@property (weak, nonatomic) IBOutlet UILabel* LBElectricMeterMonthReadCount;
@property (weak, nonatomic) IBOutlet UILabel* LBElectricMeterMonthNoReadCount;

@property (weak, nonatomic) IBOutlet UILabel* LBGasMeterTodayReadCount;
@property (weak, nonatomic) IBOutlet UILabel* LBGasMeterMonthReadCount;
@property (weak, nonatomic) IBOutlet UILabel* LBGasMeterMonthNoReadCount;
@property (weak, nonatomic) IBOutlet UITextField* TFMeterNumber;
@property (weak, nonatomic) IBOutlet UIButton* BtnMeterNumberReadMeter;

@property (nonatomic, strong) UIButton *noScanButton;
@property (nonatomic, strong) UIButton *scanButton;
@end

@implementation YWMeterHomePageViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    self.title = @"抄表";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.BtnMeterNumberReadMeter.enabled = NO;
    self.TFMeterNumber.placeholder = @"输入表号";
    self.TFMeterNumber.delegate = self;
    
    [self.view addSubview:self.noScanButton];
    [self.view addSubview:self.scanButton];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"抄表记录" style:UIBarButtonItemStyleDone target:self action:@selector(readingMeterRecord)];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    YWWeakSelf(weakSelf);
    [[YWMeterReadingManager shareManager] requestThisMonthReadingMeterCount:^(BOOL success) {
        if (success) {
            [weakSelf showStatisticsNumber];
        }
    }];
}


- (void)showStatisticsNumber
{
    [self showWaterMeterStatisticsNumber];
    [self showElectricMeterStatisticsNumber];
    [self showGasMeterStatisticsNumber];
}

- (void)showElectricMeterStatisticsNumber
{
    //电表
    NSInteger eEquipmentTypeId = [[YWMeterReadingManager shareManager]electricMeterEquipmentTypeId];
    NSArray* electricityData = [[YWMeterReadingManager shareManager] allThisMonthReadMeterCount:eEquipmentTypeId];
    NSInteger electricMeterTotalReadCount = 0;
    NSInteger electricMeterReadedCount = 0;
    for (YWThisMonthReadingMeterCount* thisMonthReadingMeterCount in electricityData) {
        electricMeterTotalReadCount += thisMonthReadingMeterCount.total;
        electricMeterReadedCount += thisMonthReadingMeterCount.recordedAmount;
    }
    self.LBElectricMeterMonthReadCount.text = [NSString stringWithFormat:@"%ld", (long)electricMeterReadedCount];
    self.LBElectricMeterMonthNoReadCount.text = [NSString stringWithFormat:@"%ld", (long)(electricMeterTotalReadCount - electricMeterReadedCount)];
    self.LBElectricMeterTodayReadCount.text = [NSString stringWithFormat:@"%ld", (long)[[YWMeterReadingManager shareManager] toDayReadMeterCountWithEquipmentTypeId:eEquipmentTypeId]];
}

- (void)showWaterMeterStatisticsNumber
{
    //水表
    NSInteger wEquipmentTypeId = [[YWMeterReadingManager shareManager]waterMeterEquipmentTypeId];
    NSArray* waterData = [[YWMeterReadingManager shareManager] allThisMonthReadMeterCount:wEquipmentTypeId];
    NSInteger waterMeterTotalReadCount = 0;
    NSInteger waterMeterReadedCount = 0;
    for (YWThisMonthReadingMeterCount* thisMonthReadingMeterCount in waterData) {
        waterMeterTotalReadCount += thisMonthReadingMeterCount.total;
        waterMeterReadedCount += thisMonthReadingMeterCount.recordedAmount;
    }
    self.LBWaterMeterMonthReadCount.text = [NSString stringWithFormat:@"%ld", (long)waterMeterReadedCount];
    self.LBWaterMeterMonthNoReadCount.text = [NSString stringWithFormat:@"%ld", (long)(waterMeterTotalReadCount - waterMeterReadedCount)];
    self.LBWaterMeterTodayReadCount.text = [NSString stringWithFormat:@"%ld", (long)[[YWMeterReadingManager shareManager] toDayReadMeterCountWithEquipmentTypeId:wEquipmentTypeId]];
}

- (void)showGasMeterStatisticsNumber
{
    //煤气
    NSInteger gEquipmentTypeId = [[YWMeterReadingManager shareManager]gasMeterEquipmentTypeId];
    NSArray* gasData = [[YWMeterReadingManager shareManager] allThisMonthReadMeterCount:gEquipmentTypeId];
    NSInteger gasMeterTotalReadCount = 0;
    NSInteger gasMeterReadedCount = 0;
    for (YWThisMonthReadingMeterCount* thisMonthReadingMeterCount in gasData) {
        gasMeterTotalReadCount += thisMonthReadingMeterCount.total;
        gasMeterReadedCount += thisMonthReadingMeterCount.recordedAmount;
    }
    self.LBGasMeterMonthReadCount.text = [NSString stringWithFormat:@"%ld", (long)gasMeterReadedCount];
    self.LBGasMeterMonthNoReadCount.text = [NSString stringWithFormat:@"%ld", (long)(gasMeterTotalReadCount - gasMeterReadedCount)];
    self.LBGasMeterTodayReadCount.text = [NSString stringWithFormat:@"%ld", (long)[[YWMeterReadingManager shareManager] toDayReadMeterCountWithEquipmentTypeId:gEquipmentTypeId]];
}

- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event
{
    [self.view endEditing:YES];
}

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string

{
    NSString* text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (text.length > 0) {
        self.BtnMeterNumberReadMeter.enabled = YES;
    }
    else {
        self.BtnMeterNumberReadMeter.enabled = NO;
    }
    return YES;
}

- (IBAction)meterNumberReadMeter:(id)sender
{
    [self.view endEditing:YES];
    YWEquipment* equipment = [[YWMeterReadingManager shareManager] meterNumber:self.TFMeterNumber.text];
    if (equipment) {
        YWDoMeterReadingTableViewController* meterReadingVC = [[YWDoMeterReadingTableViewController alloc] init];
        meterReadingVC.equipment = equipment;
        meterReadingVC.enterFromButtonOrNoQrcode = YES;
        [self.navigationController pushViewController:meterReadingVC animated:YES];
    }
    else {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextMeterNumberReadingNoMeter, nil)];
    }
}

#pragma mark -IBAction
- (void)readingMeterRecord
{
    YWMeterReadingRecordViewController* vc = [[YWMeterReadingRecordViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


- (IBAction)scanQrcodeReadMeter:(id)sender
{
    [[YWQrcodeManager shareManager]clickScanButtonWithType:YWQrcodeScanTypeMeterReading ViewController:self completionBlock:^(NSString *qrcodeId, QRCodeReaderViewController *qrCodeReaderViewController) {
        //上传扫码日志
        [[YWQrcodeManager shareManager] postQrcodeLogWithQrcodeId:qrcodeId qrcodeLogType:YWQrcodeLogTypeMeterReading];
        dispatch_async(dispatch_get_main_queue(), ^{
            //            [qrCodeReaderViewController dismissViewControllerAnimated:NO completion:^{
            [self qrcodeOrNoScanWithEquipment:[[YWMeterReadingManager shareManager] meterQRCoder:qrcodeId] qrCodeReaderVC:qrCodeReaderViewController scan:YES];
            //            }];
        });
    }];
}

- (void)clickScanBtnEvent:(id)sender{
    [self scanQrcodeReadMeter:sender];
}

- (void)handleNoScanBtnEvent:(id)sender{
    NSInteger value = [[[NSUserDefaults standardUserDefaults] objectForKey:KYWNoQrcodeTypeMeterReadingKey] integerValue];
    if (value==1) {
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"无码工作已被管理员禁止" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        YWSelectMeterReadingEquipmentTableViewController *selectMeterEquiVC = [[YWSelectMeterReadingEquipmentTableViewController alloc] init];
        __weak __typeof(&*selectMeterEquiVC) weakSelectMeterEquiVC = selectMeterEquiVC;
        selectMeterEquiVC.meterReadingBlock = ^(YWEquipment *equipment) {
            __strong __typeof(&*weakSelectMeterEquiVC) strongSelectMeterEquiVC = weakSelectMeterEquiVC;
            [self qrcodeOrNoScanWithEquipment:equipment qrCodeReaderVC:strongSelectMeterEquiVC scan:NO];
        };
        [self.navigationController pushViewController:selectMeterEquiVC animated:YES];
    }
}

- (void)qrcodeOrNoScanWithEquipment:(YWEquipment*)equipment qrCodeReaderVC:(UIViewController*)qrCodeReaderVC scan:(BOOL)isScan{
    if (equipment) {
        YWDoMeterReadingTableViewController* meterReadingVC = [[YWDoMeterReadingTableViewController alloc] init];
        meterReadingVC.equipment = equipment;
        meterReadingVC.enterFromButtonOrNoQrcode = !isScan;
        [qrCodeReaderVC.navigationController pushViewController:meterReadingVC animated:YES];
    }
    else {
        YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
        senmVC.showContent = NSLocalizedString(kTextMeterReadingNoMeter, nil);
        [qrCodeReaderVC.navigationController pushViewController:senmVC animated:YES];
    }
}

- (UIButton *)scanButton{
    if (!_scanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"扫码" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(clickScanBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(SCREEN_WIDTH/4, SCREEN_HEIGHT-64-KbottomViewH, SCREEN_WIDTH/4*3, KbottomViewH);
        _scanButton = button;
    }
    return _scanButton;
}
- (UIButton *)noScanButton{
    if (!_noScanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"无码" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customYellowColor];
        [button addTarget:self action:@selector(handleNoScanBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(0, SCREEN_HEIGHT-64-KbottomViewH, SCREEN_WIDTH/4, KbottomViewH);
        _noScanButton = button;
    }
    return _noScanButton;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //键盘弹起的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //键盘隐藏的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark - UIKeyboardNSNotification
- (void)keyboardWillShow:(NSNotification*)notification
{
    NSDictionary* info = [notification userInfo];
    NSValue* value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [self moveUpBgViewWithKeyboardHeight:keyboardSize.height animationDuration:duration];
}

- (void)keyboardWillHide:(NSNotification*)notification
{
    NSDictionary* info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [self moveDownBgViewWithDuration:duration];
}

- (void)moveUpBgViewWithKeyboardHeight:(CGFloat)height animationDuration:(CGFloat)duration
{
    CGRect parentRect = [self.TFMeterNumber.superview convertRect:self.TFMeterNumber.frame toView:self.view];
    CGFloat textViewMaxY = CGRectGetMaxY(parentRect);
    if (self.view.height - textViewMaxY >= height) {
        return;
    }
    [UIView animateWithDuration:duration animations:^{
        self.view.y = -(height - self.view.height + textViewMaxY);
    }];
}

- (void)moveDownBgViewWithDuration:(CGFloat)duration
{
    if (64 == self.view.y) {
        return;
    }
    [UIView animateWithDuration:duration animations:^{
        self.view.y = 64;
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
